package com.example.caoben_back.config;

import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean
    public ModularRealmAuthenticator authenticator() {
        return new ModularRealmAuthenticator();
    }

    @Bean
    public ModularRealmAuthorizer authorizer() {
        return new ModularRealmAuthorizer();
    }

    @Bean
    public SessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        // 禁用 Session ID Cookie，因为我们使用 JWT 进行无状态认证
        sessionManager.setSessionIdCookieEnabled(false);
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        return sessionManager;
    }

    @Bean
    public SecurityManager securityManager(Realm jwtRealm, 
                                        ModularRealmAuthenticator authenticator,
                                        ModularRealmAuthorizer authorizer,
                                        SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(jwtRealm);
        securityManager.setAuthenticator(authenticator);
        securityManager.setAuthorizer(authorizer);
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        
        // 公开接口无需认证
        chainDefinition.addPathDefinition("/user/login", "anon");
        chainDefinition.addPathDefinition("/user/register", "anon");
        chainDefinition.addPathDefinition("/weather/province/list", "anon");
        chainDefinition.addPathDefinition("/post/list", "anon");
        
        // 静态资源和公开页面
        chainDefinition.addPathDefinition("/login.jsp", "anon");
        chainDefinition.addPathDefinition("/favicon.ico", "anon");
        
        // 其他接口都需要认证
        // 使用自定义的 JWT 过滤器进行认证，这里设置为 anon 允许通过
        chainDefinition.addPathDefinition("/**", "anon");
        
        return chainDefinition;
    }
}